package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/*
* 实例化与当前Test4所在同一个包中被注解@AutoRunClass标注的类并调用其中被注解@AutoRunMethod标注的方法
* */
public class Test4 {
    public static void main(String[] args) throws Exception {
        File dir = new File(
                Test3.class.getResource(".").toURI()
        );
        File[] files = dir.listFiles(f->f.getName().endsWith(".class"));
        for (File file:files){
            String fileName = file.getName().substring(0,file.getName().indexOf("."));
            String packageName = Test3.class.getPackage().getName();
            Class cls = Class.forName(packageName+"."+fileName);
            if(cls.isAnnotationPresent(AutoRunClass.class)){
                Object obj = cls.newInstance();
                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods){
                    if(method.isAnnotationPresent(AutoRunMethod.class)){
                        method.invoke(obj);
                    }
                }
            }
        }
    }
}
